package com.sky.service.impl;

import com.sky.dto.DataOverViewQueryDTO;
import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.entity.User;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WorkspaceService workspaceService;

    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        ArrayList<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);

        // 获取最小时间
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        // 获取最大时间
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        // 如果开始时间小于结束时间，添加一天并判断
        while (begin.isBefore(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        // 数据库入参
        Map<String, Object> map = new HashMap<>();
        map.put("begin", beginTime);
        map.put("end", endTime);
        map.put("status", 5);
        // 查询订单数据
        List<Orders> list = orderMapper.selectCountByMap(map);

        // 转换出参为 date: amount
        HashMap<Object, Object> map2 = new HashMap<>();
        for (Orders orders : list) {
            map2.put(orders.getOrderTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")), orders.getAmount());
        }

        // 遍历日期集合
        StringBuilder dateListStr = new StringBuilder();
        StringBuilder turnoverList = new StringBuilder();
        for (LocalDate date : dateList) {
            String format = date.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            dateListStr.append(format).append(",");
            if (map2.get(format) != null) {
                turnoverList.append(map2.get(format)).append(",");
            } else {
                turnoverList.append(BigDecimal.ZERO).append(",");
            }
        }

        // 封装数据
        TurnoverReportVO turnoverReportVO = new TurnoverReportVO();
        turnoverReportVO.setDateList(dateListStr.toString());
        turnoverReportVO.setTurnoverList(turnoverList.toString());
        return turnoverReportVO;
    }

    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        ArrayList<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);

        // 如果开始时间小于结束时间，添加一天并判断
        while (!begin.isEqual(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        ArrayList<Integer> newUserList = new ArrayList<>();
        ArrayList<Integer> totalUserList = new ArrayList<>();

        for (LocalDate localDate : dateList) {
            // 数据库入参
            Map<String, Object> map = new HashMap<>();
            map.put("end", LocalDateTime.of(localDate, LocalTime.MAX));
            // 总用户数量
            int totalUserCount = userMapper.getCountByDate(map);


            // 当天新增的用户总数
            map.put("begin", LocalDateTime.of(localDate, LocalTime.MIN));
            int newUserCount = userMapper.getCountByDate(map);


            totalUserList.add(totalUserCount);
            newUserList.add(newUserCount);
        }

        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .build();
    }

    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        ArrayList<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);

        // 如果开始时间小于结束时间，添加一天并判断
        while (!begin.isEqual(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        ArrayList<Integer> orderCountList = new ArrayList<>();
        ArrayList<Integer> validOrderCountList = new ArrayList<>();
        Integer totalOrderCount = 0;
        Integer validOrderCount = 0;

        for (LocalDate localDate : dateList) {
            Map<String, Object> map = new HashMap<>();
            map.put("begin", LocalDateTime.of(localDate, LocalTime.MIN));
            map.put("end", LocalDateTime.of(localDate, LocalTime.MAX));

            // 查询每天的订单总数
            Integer count = orderMapper.selectCountByDate(map);
            orderCountList.add(count);

            // 查询每天的有效订单总数
            map.put("status", Orders.COMPLETED);
            Integer validOrderCountTmp = orderMapper.selectCountByDate(map);
            validOrderCountList.add(validOrderCountTmp);

        }

        // 订单总数
        totalOrderCount = orderMapper.selectCountByDate(new HashMap());

        // 有效订单数
        validOrderCount = orderMapper.getCountByStatus(Orders.COMPLETED);

        double orderCompletionRate = 0.0d;
        if (totalOrderCount != 0) {
            orderCompletionRate = validOrderCount / totalOrderCount;
        }

        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {
        Map<String, Object> map = new HashMap<>();
        map.put("startTime", LocalDateTime.of(begin, LocalTime.MIN));
        map.put("endTime", LocalDateTime.of(end, LocalTime.MAX));
        map.put("status", Orders.COMPLETED);

        List<GoodsSalesDTO> list = orderMapper.getSalesTop(map);

        List<String> names = list.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> numbers = list.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());

        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(names, ","))
                .numberList(StringUtils.join(numbers, ","))
                .build();
    }

    @Override
    public void export(HttpServletResponse response) {
        //1. 查询数据库，获取营业数据---查询最近30天的运营数据
        LocalDate todayDate = LocalDate.now();
        LocalDate beginDate = todayDate.plusDays(-30);
        LocalDateTime todayDateTimeMax = LocalDateTime.of(todayDate, LocalTime.MAX);
        LocalDateTime beginDateTimeMin = LocalDateTime.of(todayDate.plusDays(-30), LocalTime.MIN);
        BusinessDataVO businessDataVO = workspaceService.businessData(beginDateTimeMin, todayDateTimeMax);

        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("templates/运营数据报表模板.xlsx");
        XSSFWorkbook excel = null;
        XSSFSheet sheet = null;
        XSSFRow row = null;
        try {
            excel = new XSSFWorkbook(resourceAsStream);
            sheet = excel.getSheetAt(0);

            row = sheet.getRow(1);
            row.getCell(1).setCellValue(beginDate + "至" +  todayDate);


            row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessDataVO.getTurnover());
            row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessDataVO.getNewUsers());

            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            row.getCell(4).setCellValue(businessDataVO.getUnitPrice());



            for (int i = 0; i < 30; i++) {
                LocalDate localDate = beginDate.plusDays(i);
                LocalDateTime localDateMin = LocalDateTime.of(localDate, LocalTime.MIN);
                LocalDateTime localDateMax = LocalDateTime.of(localDate, LocalTime.MAX);
                businessDataVO = workspaceService.businessData(localDateMin, localDateMax);

                row = sheet.getRow(i + 7);
                row.getCell(1).setCellValue(localDate.toString());
                row.getCell(2).setCellValue(businessDataVO.getTurnover());
                row.getCell(3).setCellValue(businessDataVO.getValidOrderCount());
                row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessDataVO.getUnitPrice());
                row.getCell(6).setCellValue(businessDataVO.getNewUsers());
            }

            ServletOutputStream out = response.getOutputStream();
            excel.write(out);

            out.close();
            excel.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
